/*
 * TCSS 422 Web Spider Project
 * Group Money: Al McKenzie, Michael Pitts, Taylor Zielske
 */
package model.domain;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import model.URLInputCooker;

/**
 * A domain that has lists, which could be used to accept or reject a potential url.
 * 
 * @author Michael Pitts
 * @version Oct 19, 2011
 */
public abstract class AbstractListDomain extends OpenDomain {
	
	/**
	 * Directories the spider may be allowed to search, or banned from.
	 */
	private final Set<String> my_directories;
	
	/**
	 * Specific urls the spider is allowed to search, or banned from.
	 */
	private final Set<String> my_urls;

	/**
	 * Creates a new List Domain, which allows or excludes certain urls.
	 * @param the_domain is the string representation of the domain.
	 * @param the_cooker is the cooker that will be used to submit new urls to.
	 * @param the_directories are the web directories to remember.
	 * @param the_urls are the specific urls to remember.
	 */
	public AbstractListDomain(final String the_domain, final URLInputCooker the_cooker,
			final String[] the_directories, final String[] the_urls) {
		super(the_domain, the_cooker);
		my_directories = getSet(the_directories);
		my_urls = getSet(the_urls);
		}
	
	/**
	 * Gets a read only set of Strings that can be searched quickly.
	 * @param the_strings are the strings to be loaded into the set.
	 * @return a new unmodifiable set that contains strings.
	 * @see Collections#unmodifiableSet(Set)
	 */
	private Set<String> getSet(final String[] the_strings) {
		final Set<String> set = new HashSet<String>();
		for (String string : the_strings) {
			set.add(string);
		}
		return Collections.unmodifiableSet(set);
	}

	/**
	 * Returns true if the given url would be found in the lists, either directly
	 * or if the url would be within a directory on the list.
	 * @param the_url is the url to check.
	 * @return true if the url is in the list somewhere, false otherwise.
	 */
	public final boolean listedURL(final String the_url) {
		boolean stop = my_urls.contains(the_url);
		int index; // catches the last index of a '/', which indicates a directory
		String reduced = the_url; // will be reduced in length to check directories
		while (!stop && reduced.length() > ("http://".length() + getDomain().length() + 1)) {
			reduced = reduced.substring(0, reduced.length() - 1);
			index = reduced.lastIndexOf("/") + 1; // remove last directory
			reduced = reduced.substring(0, index);
			stop = my_directories.contains(reduced);
		}
		return stop;
	}
}
